from PyQt5.QtWidgets import QWidget, QFileDialog, QMessageBox
import os

# 导入窗体内容
from design.settingDlg import *

from common.logger import logger
from common.retcode import RetCode
from common.types import SettingInfo
from common.utils import center_window_on_screen

# 创建 MainWin 类并传入Ui_MainWindow
class SettingDlg(QWidget, Ui_SettingDlg):
	def __init__(self, parent=None):
		super(SettingDlg, self).__init__(parent)
		self.setupUi(self)
		center_window_on_screen(self)

		self.pushButtonDownDirSel.clicked.connect(self.onClickedDownDirSel)
		self.pushButtonSave.clicked.connect(self.onClickedSave)

		self._sess_wp = None

	def reset(self, sess_wp):
		self._sess_wp = sess_wp
		setting_info = sess_wp.get_setting_info()

		cur_down_dir = ""
		if setting_info:
			cur_down_dir = setting_info.downDir
		self.lineEditDownDir.setText(cur_down_dir)

	def onClickedDownDirSel(self):
		cur_down_dir = self.lineEditDownDir.text()
		if len(cur_down_dir) <= 0 or (not os.path.exists(cur_down_dir)):
			setting_info = self._sess_wp.get_setting_info()
			if not setting_info:
				QMessageBox.information(self, "失败", "找不到当前用户的设置信息")
				return
			cur_down_dir = setting_info.downDir
			if not os.path.exists(cur_down_dir):
				os.makedirs(cur_down_dir)

		# print(f'cur_down_dir: {cur_down_dir}')

		downDir = QFileDialog.getExistingDirectory(self, "浏览",  cur_down_dir)
		self.lineEditDownDir.setText(downDir)

	def onClickedSave(self):
		setting_info = SettingInfo()
		setting_info.downDir = self.lineEditDownDir.text()

		apply_to_all = self.checkBoxApplyToAll.isChecked()
		if self._sess_wp.save_setting_info(setting_info, apply_to_all):
			QMessageBox.information(self, "成功", "保存设置成功")
		else:
			QMessageBox.information(self, "失败", "保存设置失败")
